<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/4
 * Time: 10:27:42
 */

namespace Service\CommodityService;

use App\Model\BbcModel\GoodsBrand;
use Service\Code\Normal;
use App\Model\BbcModel\Goods;
use Service\BaseService;

/**
 * 品牌管理
 */
class GoodsBrandService extends BaseService
{
    public function makeWhere(array $param)
    {
        $where = [
            ['cid','=',$param['cid']],
            ['sid','=',$param['sid']],
            ['df','=',0]
        ];

        if(isset($param['name']) && $param['name'] != ''){
            $where[] = ['name','like',"%{$param['name']}%"];
        }

        if(isset($param['start_time']) && $param['start_time'] != ''){
            $start_time = strtotime($param['start_time']);
            $where[] = ['md','>',$start_time];
        }

        if(isset($param['end_time']) && $param['end_time'] != ''){
            $end_time = strtotime($param['end_time']);
            $where[] = ['md','<',$end_time];
        }

        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=',$param['status']];
        }

        if(isset($param['type']) && $param['type'] != ''){
            $where[] = ['type','=',$param['type']];
        }

        return $where;
    }
    public function brandList(array $param)
    {
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        $where = $this->makeWhere($param);
        $data_list = GoodsBrand::instance()
            ->where($where)
            ->orderByRaw('country_rec_sort asc,id desc')
            ->paginate($limit, ['id','name','type','pic','banner_image','info','sort','status','md'], 'page', $page);

        $total = $data_list->total();
        $list = $data_list->items();
        foreach ($list as &$v){
            if($v['md']){
                $v['md'] = date('Y-m-d H:i:s',$v['md']);
            }
            $v['goods_num'] = Goods::instance()->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'df'=>0,'brand_id'=>$v['id']])->count();
            $v['type_text'] = $v['type'] == 1 ? '供应商品牌':'自建品牌';
            if (!empty($v['pic']) && strpos($v['pic'],'http')===false) {
                $v['pic'] = pre_image_url(). $v['pic'] ;
            }

            $v['status_text'] = $v['status'] == 1 ? '启用':'禁用';
        }

        $brand_status_list = GoodsBrand::instance()
            ->where($where)
            ->pluck('status')->toArray();

        if(!$brand_status_list){
            $brand_status_map = array_count_values($brand_status_list);
        }else{
            $brand_status_map = [];
        }

        $enable_num = $brand_status_map[1] ?? 0;
        $disable_num = $brand_status_map[0] ?? 0;

        return Normal::returnCode(Normal::SUC,'请求成功',['list'=>$list,'total'=>$total,'enable_num'=>$enable_num,'disable_num'=>$disable_num]);
    }
    public function add(array $param)
    {
        if(empty($param['name'])){
            return Normal::returnCode(Normal::FAIL,'缺少品牌名称');
        }

        if(empty($param['pic'])){
            return Normal::returnCode(Normal::FAIL,'缺少品牌LOGO');
        }

        $info = GoodsBrand::instance()
            ->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'df'=>0,'name'=>$param['name'],'type'=>1])
            ->first();
        if($info){
            return Normal::returnCode(Normal::FAIL,'自建品牌不能与供应商品牌同名，请修改确认后再操作');
        }

        $max_sort = GoodsBrand::instance()
            ->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'df'=>0])
            ->max('sort');
        $res = GoodsBrand::instance()
            ->insert([
                'type' => 2,
                'cid' => $param['cid'],
                'sid' => $param['sid'],
                'name'=> $param['name'],
                'pic'=> $param['pic'],
                'banner_image' => $param['banner_image'] ?? '',
                'info' => $param['info'] ?? '',
                'sort' => $param['sort'] ?? $max_sort + 1,
                'cd' => time(),
                'md' => time(),
            ]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }
    public function details(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,'缺少品牌ID');
        }

        $info = GoodsBrand::instance()
            ->where(['id'=>$param['id'],'df'=>0,'cid'=>$param['cid'],'sid'=>$param['sid']])
            ->select('id','type','name','info','pic','sort','banner_image')
            ->first();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'品牌不存在');
        }

        $info['type'] = $info['type'] == 1 ? '供应商' : '自建';

        if($info['banner_image'] && !preg_match("/^http(s)?:\\/\\/.+/",$info['banner_image'])){
            $info['banner_image'] = pre_image_url().$info['banner_image'];
        }

        return Normal::returnCode(Normal::SUC,'请求成功',$info);
    }
    public function edit(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,'缺少品牌ID');
        }

        if(empty($param['name'])){
            return Normal::returnCode(Normal::FAIL,'品牌名称不能为空');
        }
        if(empty($param['pic'])){
            return Normal::returnCode(Normal::FAIL,'品牌LOGO不能为空');
        }

        $info = GoodsBrand::instance()
            ->where(['id'=>$param['id'],'df'=>0,'cid'=>$param['cid'],'sid'=>$param['sid']])
            ->first();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'品牌不存在');
        }

        $status = GoodsBrand::instance()
            ->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'df'=>0,'name'=>$param['name'],'type'=>1])
            ->first();
        if($status){
            return Normal::returnCode(Normal::FAIL,'自建品牌不能与供应商品牌同名，请修改确认后再操作');
        }

        $res = GoodsBrand::instance()
            ->update([
                'name'=> $param['name'],
                'pic'=> $param['pic'],
                'banner_image' => $param['banner_image'] ?? '',
                'info' => $param['info'] ?? '',
                'sort' => $param['sort'] ?? $info['sort'],
                'md' => time(),
            ]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'编辑失败');
        }
        return Normal::returnCode(Normal::SUC,'编辑成功');

    }
    public function changeBrandStatus(array $param)
    {
        if(!isset($param['brand_ids']) || !$param['brand_ids']){
            return Normal::returnCode(Normal::FAIL,'请选择品牌');
        }
        if(!isset($param['status']) || !in_array($param['status'],[0,1])){
            return Normal::returnCode(Normal::FAIL,'缺少更改的状态参数');
        }

        $status = $param['status'];
        $res = GoodsBrand::instance()
            ->where(['cid'=>$param['cid'],'sid'=>$param['sid']])
            ->whereIn('id',$param['brand_ids'])
            ->update(['status'=>$status,'md'=>time()]);

        if(!$res){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
    public function delBrand(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,'缺少品牌ID');
        }

        $info = GoodsBrand::instance()
            ->where(['cid'=>$param['cid'],'sid'=>$param['sid'],'df'=>0,'id'=>$param['id']])
            ->first();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'品牌不存在');
        }
        if($info['type'] != 2){
            return Normal::returnCode(Normal::FAIL,'只能删除自建品牌');
        }
        $res = GoodsBrand::instance()
            ->where('id',$param['id'])
            ->update(['df'=>1,'md'=>time()]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    public function moveUpDown($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少品牌ID');
        }
        if(!isset($param['type']) || !$param['type']){
            return Normal::returnCode(Normal::FAIL,'缺少移动类型参数');
        }
        $table = GoodsBrand::instance();
        $where = [
            ['cid','=',$param['cid']],
            ['sid','=',$param['sid']],
            ['df','=',0],
        ];
        return (new \Service\MoveUpDownService\MoveUpDownService())->moveUpDown($param['id'],$param['type'],$table,$where,'sort');
    }

    public function setTop($param) : array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少品牌ID');
        }
        if(!isset($param['type']) || !$param['type']){
            return Normal::returnCode(Normal::FAIL,'缺少置顶参数');
        }

        $table = GoodsBrand::instance();
        $where = [
            ['cid','=',$param['cid']],
            ['sid','=',$param['sid']],
            ['df','=',0],
        ];
        $res = (new \Service\MoveUpDownService\MoveUpDownService())->setTop($param['id'],$table,$where,'sort',$param['type']);
        if($res['code'] != Normal::SUC){
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
}